package HTTP;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class HttpClientTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		System.out.println("*** 1.--------------------");
		ejem1("http://localhost:8080/string.txt");
		
		//System.out.println("\n*** 2.------------------");
		//ejem2();
	}

	/**
	 * Ejemplo de uso de las librerias Commons-HttpClient de Apache
	 * 
	 * Este programa llama al sitio teqi.org e imprime el resultado en la
	 * pantalla
	 * 
	 */
	public static void ejem1(String url) {
		
		// Crear cliente HTTP
		HttpClient client = new HttpClient();
		
		// Crear tipo de llamada 'Get'
		HttpMethod get = new GetMethod(url);
		String str = "";
		try {
			// Executar metodo 'Get' y llamar a la pagina 'url'
			client.executeMethod(get);
			// Poner el resultado en una variable
			str = get.getResponseBodyAsString();
		} catch (HttpException e) {
			// Tienes que capturar este tipo de exception
			e.printStackTrace();
		} catch (IOException e) {
			// Tienes que capturar este tipo de exception
			e.printStackTrace();
		}
		// Imprime el contenido de la llamada
		System.out.println(str);
	}

	public static void ejem2(String url) {
		
		// Create an instance of HttpClient.
		HttpClient client = new HttpClient();

		// Create a method instance.
		HttpMethod method = new PostMethod(url);

		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);

			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + method.getStatusLine());
			}

			// Read the response body.
			String responseBody = method.getResponseBodyAsString();

			// Deal with the response.
			// Use caution: ensure correct character encoding and is not binary data
			System.out.println(responseBody);

		} catch (HttpException e) {
			System.err.println("Fatal protocol violation: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Fatal transport error: " + e.getMessage());
			e.printStackTrace();
		} finally {
			// Release the connection.
			method.releaseConnection();
		}
	}
}